package cn.lngaosu.lwyd.module.integration.service.weixinvideoliverecord;

import cn.hutool.core.collection.CollUtil;
import cn.lngaosu.lwyd.framework.common.util.http.HttpUtils;
import cn.lngaosu.lwyd.module.infra.service.config.ConfigService;
import cn.lngaosu.lwyd.module.integration.service.apptoken.AppTokenService;
import cn.lngaosu.lwyd.module.integration.service.weixinarticle.WeixinArticleServiceImpl;
import cn.lngaosu.lwyd.module.system.dal.dataobject.webinterfacelog.WebinterfaceLogDO;
import cn.lngaosu.lwyd.module.system.dal.mysql.webinterfacelog.WebinterfaceLogMapper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.lngaosu.lwyd.module.integration.controller.admin.weixinvideoliverecord.vo.*;
import cn.lngaosu.lwyd.module.integration.dal.dataobject.weixinvideoliverecord.WeixinvideoLiverecordDO;
import cn.lngaosu.lwyd.framework.common.pojo.PageResult;
import cn.lngaosu.lwyd.framework.common.pojo.PageParam;
import cn.lngaosu.lwyd.framework.common.util.object.BeanUtils;

import cn.lngaosu.lwyd.module.integration.dal.mysql.weixinvideoliverecord.WeixinvideoLiverecordMapper;

import static cn.lngaosu.lwyd.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.lngaosu.lwyd.framework.common.util.collection.CollectionUtils.convertList;
import static cn.lngaosu.lwyd.framework.common.util.collection.CollectionUtils.diffList;
import static cn.lngaosu.lwyd.module.integration.enums.ErrorCodeConstants.*;

/**
 * 微信视频号直播记录 Service 实现类
 *
 * @author 张恒
 */
@Service
@Validated
public class WeixinvideoLiverecordServiceImpl implements WeixinvideoLiverecordService {
    private static final Logger logger = LoggerFactory.getLogger(WeixinvideoLiverecordServiceImpl.class);

    @Resource
    private WeixinvideoLiverecordMapper weixinvideoLiverecordMapper;
    @Resource
    private AppTokenService appTokenService;
    @Resource
    private ConfigService configService;
    @Resource
    private WebinterfaceLogMapper webinterfaceLogMapper;

    @Override
    public Long createWeixinvideoLiverecord(WeixinvideoLiverecordSaveReqVO createReqVO) {
        // 插入
        WeixinvideoLiverecordDO weixinvideoLiverecord = BeanUtils.toBean(createReqVO, WeixinvideoLiverecordDO.class);
        weixinvideoLiverecordMapper.insert(weixinvideoLiverecord);
        // 返回
        return weixinvideoLiverecord.getId();
    }

    @Override
    public void updateWeixinvideoLiverecord(WeixinvideoLiverecordSaveReqVO updateReqVO) {
        // 校验存在
        validateWeixinvideoLiverecordExists(updateReqVO.getId());
        // 更新
        WeixinvideoLiverecordDO updateObj = BeanUtils.toBean(updateReqVO, WeixinvideoLiverecordDO.class);
        weixinvideoLiverecordMapper.updateById(updateObj);
    }

    @Override
    public void deleteWeixinvideoLiverecord(Long id) {
        // 校验存在
        validateWeixinvideoLiverecordExists(id);
        // 删除
        weixinvideoLiverecordMapper.deleteById(id);
    }

    @Override
        public void deleteWeixinvideoLiverecordListByIds(List<Long> ids) {
        // 校验存在
        validateWeixinvideoLiverecordExists(ids);
        // 删除
        weixinvideoLiverecordMapper.deleteByIds(ids);
        }

    private void validateWeixinvideoLiverecordExists(List<Long> ids) {
        List<WeixinvideoLiverecordDO> list = weixinvideoLiverecordMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(WEIXINVIDEO_LIVERECORD_NOT_EXISTS);
        }
    }

    private void validateWeixinvideoLiverecordExists(Long id) {
        if (weixinvideoLiverecordMapper.selectById(id) == null) {
            throw exception(WEIXINVIDEO_LIVERECORD_NOT_EXISTS);
        }
    }

    @Override
    public WeixinvideoLiverecordDO getWeixinvideoLiverecord(Long id) {
        return weixinvideoLiverecordMapper.selectById(id);
    }

    @Override
    public PageResult<WeixinvideoLiverecordDO> getWeixinvideoLiverecordPage(WeixinvideoLiverecordPageReqVO pageReqVO) {
        return weixinvideoLiverecordMapper.selectPage(pageReqVO);
    }

    @Override
    public void syncWeixinvideoLiverecord() {
        // 获取token
        String weixinVideoToken = appTokenService.getWeixinVideoToken();
        if (StringUtils.isEmpty(weixinVideoToken)) {
            throw exception(WEIXINVIDEO_TOKEN_NOT_EXISTS);
        }

        // 接口配置
        String configValue = configService.getConfigValueByKey("weixinVideoConfig");
        if (StringUtils.isEmpty(configValue)) {
            throw exception(INTERFACE_CONFIG_NOT_EXISTS);
        }

        JSONObject configJo = JSONObject.parseObject(configValue);
        // 接口开关
        String onOff = configJo.getString("onOff");
        if (!"on".equals(onOff)) {
            throw exception(INTERFACE_CONFIG_NOT_EXISTS);
        }

        // 获取地址
        String finderliverecordlistUrl = configJo.getString("finderliverecordlistUrl");
        finderliverecordlistUrl = finderliverecordlistUrl + "?access_token=" + weixinVideoToken;

        // 构造请求参数
        JSONObject params = new JSONObject();

        // 初始化日志数据（默认成功）
        WebinterfaceLogDO webinterfaceLogDO = new WebinterfaceLogDO();
        webinterfaceLogDO.setInterfaceSystemName("微信视频号");
        webinterfaceLogDO.setInterfaceName("获取视频号的当前直播中记录");
        webinterfaceLogDO.setInterfaceUrl(finderliverecordlistUrl);
        webinterfaceLogDO.setInterfaceRequestMethod("POST");
        webinterfaceLogDO.setInterfaceParam(JSONObject.toJSONString(params));
        webinterfaceLogDO.setInterfaceStatus("成功");
        webinterfaceLogMapper.insert(webinterfaceLogDO);

        try {
            String result = HttpUtils.post(finderliverecordlistUrl, new HashMap<>(), JSONObject.toJSONString(params));

            // 解析接口结果
            JSONObject resultJo = JSONObject.parseObject(result);
            Integer errcode = resultJo.getInteger("errcode");
            if (ObjectUtils.isNotEmpty(errcode) && errcode != 0) {
                webinterfaceLogDO.setInterfaceStatus("失败");
                webinterfaceLogDO.setInterfaceErrorInfo(result);
                webinterfaceLogMapper.updateById(webinterfaceLogDO);
                return;
            }
            webinterfaceLogDO.setInterfaceErrorInfo(result);
            webinterfaceLogMapper.updateById(webinterfaceLogDO);

            // 处理接口数据
            JSONArray liveList = resultJo.getJSONArray("live_list");
            for (int i = 0; i < liveList.size(); i++) {
                JSONObject jsonObject = liveList.getJSONObject(i);
                WeixinvideoLiverecordDO weixinvideoLiverecordDO = BeanUtils.toBean(jsonObject, WeixinvideoLiverecordDO.class);
                // 查询本地库中是否有该直播记录，有则更新，无则新增
                String exportId = weixinvideoLiverecordDO.getExportId();
                LambdaQueryWrapper<WeixinvideoLiverecordDO> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(WeixinvideoLiverecordDO::getExportId, exportId);
                List<WeixinvideoLiverecordDO> weixinvideoLiverecordDOS = weixinvideoLiverecordMapper.selectList(queryWrapper);
                if (CollectionUtils.isNotEmpty(weixinvideoLiverecordDOS)) {
                    weixinvideoLiverecordDO.setId(weixinvideoLiverecordDOS.get(0).getId());
                }
                weixinvideoLiverecordMapper.insertOrUpdate(weixinvideoLiverecordDO);
            }

        } catch (Exception e) {
            webinterfaceLogDO.setInterfaceStatus("失败");
            webinterfaceLogDO.setInterfaceErrorInfo(e.getMessage());
            webinterfaceLogMapper.updateById(webinterfaceLogDO);
            logger.error("微信视频号【获取视频号的当前直播中记录】接口调用失败！", e);
        }
    }

}